using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using MvcDemo.Models;
using MvcDemo.Repository;
using MvcDemo.RequestParam;

namespace MvcDemo.Controllers
{
    public class StudentController : Controller{
        public IActionResult index(){
            var efr= new EfRepository<Student>();
            var stu = efr.Table.ToList();
            return View(stu);
        }
        public IActionResult CreateOrUp(int id){
            var efr = new EfRepository<Student>();
            var stu=efr.Table.Where(x=>x.id==id).FirstOrDefault();
            return View(stu);
        }
        public IActionResult Save(StudentRequestParam request){
            var efr=new EfRepository<Student>();
            if (request.id>0)
            {
                var add=efr.GetByid(request.id);
                    add.Name=request.name;
                    add.classname=request.classname;
                    add.age=request.age;
                efr.Update(add);
            }else{
                efr.Insert(new Student{
                    Name=request.name,
                    classname=request.classname,
                    age=request.age
                });
            }
            return Ok();
        }
        public IActionResult Delect(int id){
            var efr = new EfRepository<Student>();
            efr.Delect(id);
            return RedirectToAction("index");
        }
        public IActionResult Query(QueryRequest query){
            var efr=new EfRepository<Student>();
            List<Student> students;
            if (query !=null && query.keywork!=null && query.keywork.Length!=0)
            {
                students = efr.Table.Where(x=>x.Name.Contains(query.keywork) ||
                 x.classname.Contains(query.keywork)).ToList();

            }else
            {
                students=efr.Table.ToList();
            }
            return Json(students);
        }
    }
}